import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, TimePicker, Checkbox, Row, Col, Tabs } from 'antd';
import { PlusOutlined, EditOutlined, SaveOutlined, ReloadOutlined, CopyOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { Option } = Select;
const { TabPane } = Tabs;

// 获取门店列表
const fetchStores = async () => {
  return request('/api/v1/store', {
    method: 'GET',
    params: { pageSize: 100 },
  });
};

// 获取门店营业时间
const fetchStoreTime = async (store_id) => {
  return request(`/api/v1/store/time/${store_id}`, {
    method: 'GET',
  });
};

// 保存门店营业时间
const saveStoreTime = async (data) => {
  return request('/api/v1/store/time', {
    method: 'POST',
    data,
  });
};

const StoreTime = () => {
  const [stores, setStores] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentStore, setCurrentStore] = useState(null);
  const [timeData, setTimeData] = useState([]);
  const [form] = Form.useForm();
  const [mode, setMode] = useState('simple'); // 'simple' 或 'advanced'

  // 获取门店列表
  const fetchStoreList = async () => {
    try {
      setLoading(true);
      const res = await fetchStores();
      if (res.success) {
        setStores(res.data.list || []);
        if (res.data.list && res.data.list.length > 0) {
          setCurrentStore(res.data.list[0]);
          fetchStoreTimeData(res.data.list[0].id);
        }
      } else {
        message.error(res.message || '获取门店列表失败');
      }
    } catch (error) {
      console.error('获取门店列表出错:', error);
      message.error('获取门店列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取门店营业时间
  const fetchStoreTimeData = async (store_id) => {
    try {
      setLoading(true);
      const res = await fetchStoreTime(store_id);
      if (res.success) {
        // 将后端返回的数据转换为组件所需的格式
        const data = res.data || getDefaultTimeData();
        setTimeData(data);
        form.resetFields();
      } else {
        message.error(res.message || '获取门店营业时间失败');
        setTimeData(getDefaultTimeData());
      }
    } catch (error) {
      console.error('获取门店营业时间出错:', error);
      message.error('获取门店营业时间失败');
      setTimeData(getDefaultTimeData());
    } finally {
      setLoading(false);
    }
  };

  // 获取默认时间数据
  const getDefaultTimeData = () => {
    return {
      workday: {
        isOpen: true,
        openTime: '00:00',
        closeTime: '23:59'
      },
      weekend: {
        isOpen: true,
        openTime: '00:00',
        closeTime: '23:59'
      },
      // 保留每天单独设置的选项，以便后续扩展
      daily: [
        { day: 1, dayName: '周一', isOpen: true, openTime: '00:00', closeTime: '23:59' },
        { day: 2, dayName: '周二', isOpen: true, openTime: '00:00', closeTime: '23:59' },
        { day: 3, dayName: '周三', isOpen: true, openTime: '00:00', closeTime: '23:59' },
        { day: 4, dayName: '周四', isOpen: true, openTime: '00:00', closeTime: '23:59' },
        { day: 5, dayName: '周五', isOpen: true, openTime: '00:00', closeTime: '23:59' },
        { day: 6, dayName: '周六', isOpen: true, openTime: '00:00', closeTime: '23:59' },
        { day: 7, dayName: '周日', isOpen: true, openTime: '00:00', closeTime: '23:59' }
      ]
    };
  };

  // 转换为BusinessHoursEditor格式的数据
  const convertToBusinessHoursFormat = () => {
    // 确保timeData是数组
    const dailyData = Array.isArray(timeData) ? timeData :
      (timeData && timeData.daily && Array.isArray(timeData.daily)) ? timeData.daily :
        getDefaultTimeData();

    // 从每日数据中提取工作日和周末的数据
    const workdays = Array.isArray(dailyData) ? dailyData.filter(item => item.day >= 1 && item.day <= 5) : [];
    const weekends = Array.isArray(dailyData) ? dailyData.filter(item => item.day >= 6 && item.day <= 7) : [];

    // 检查工作日是否统一
    const workdayOpenTimes = [...new Set(workdays.map(item => item.openTime))];
    const workdayCloseTimes = [...new Set(workdays.map(item => item.closeTime))];
    const workdayIsOpen = [...new Set(workdays.map(item => item.isOpen))];

    // 检查周末是否统一
    const weekendOpenTimes = [...new Set(weekends.map(item => item.openTime))];
    const weekendCloseTimes = [...new Set(weekends.map(item => item.closeTime))];
    const weekendIsOpen = [...new Set(weekends.map(item => item.isOpen))];

    return {
      workday: {
        isOpen: workdayIsOpen.length === 1 ? workdayIsOpen[0] : true,
        openTime: workdayOpenTimes.length === 1 ? workdayOpenTimes[0] : '00:00',
        closeTime: workdayCloseTimes.length === 1 ? workdayCloseTimes[0] : '23:59'
      },
      weekend: {
        isOpen: weekendIsOpen.length === 1 ? weekendIsOpen[0] : true,
        openTime: weekendOpenTimes.length === 1 ? weekendOpenTimes[0] : '00:00',
        closeTime: weekendCloseTimes.length === 1 ? weekendCloseTimes[0] : '23:59'
      },
      daily: dailyData
    };
  };

  // 从每日数据更新工作日和周末的汇总数据
  const updateSummaryFromDaily = (data) => {
    if (!data.daily || !Array.isArray(data.daily)) {
      return;
    }
    
    // 检查工作日是否统一
    const workdays = data.daily.filter(item => item.day >= 1 && item.day <= 5);
    const workdayOpenTimes = [...new Set(workdays.map(item => item.openTime))];
    const workdayCloseTimes = [...new Set(workdays.map(item => item.closeTime))];
    const workdayIsOpen = [...new Set(workdays.map(item => item.isOpen))];
    
    if (workdayOpenTimes.length === 1 && workdayCloseTimes.length === 1 && workdayIsOpen.length === 1) {
      data.workday = {
        isOpen: workdayIsOpen[0],
        openTime: workdayOpenTimes[0],
        closeTime: workdayCloseTimes[0]
      };
    }
    
    // 检查周末是否统一
    const weekends = data.daily.filter(item => item.day >= 6 && item.day <= 7);
    const weekendOpenTimes = [...new Set(weekends.map(item => item.openTime))];
    const weekendCloseTimes = [...new Set(weekends.map(item => item.closeTime))];
    const weekendIsOpen = [...new Set(weekends.map(item => item.isOpen))];
    
    if (weekendOpenTimes.length === 1 && weekendCloseTimes.length === 1 && weekendIsOpen.length === 1) {
      data.weekend = {
        isOpen: weekendIsOpen[0],
        openTime: weekendOpenTimes[0],
        closeTime: weekendCloseTimes[0]
      };
    }
  };
  
  // 从BusinessHoursEditor格式转换为每日数据
  const convertFromBusinessHoursFormat = (data) => {
    if (data.daily && Array.isArray(data.daily)) {
      return data.daily;
    }

    // 如果没有daily数据，则根据workday和weekend构建
    const result = [];
    const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

    for (let i = 0; i < 7; i++) {
      const day = i + 1;
      const isWeekend = day >= 6;
      const timeSettings = isWeekend ? data.weekend : data.workday;

      result.push({
        day,
        dayName: weekdays[i],
        isOpen: timeSettings.isOpen,
        openTime: timeSettings.openTime,
        closeTime: timeSettings.closeTime
      });
    }

    return result;
  };

  useEffect(() => {
    fetchStoreList();
  }, []);

  // 处理门店变更
  const handleStoreChange = (store_id) => {
    const store = stores.find((item) => item.id === store_id);
    setCurrentStore(store);
    fetchStoreTimeData(store_id);
  };

  // 处理时间变更 - 高级模式
  const handleTimeChange = (day, field, value) => {
    // 创建timeData的深拷贝，保持原有结构
    const newTimeData = { ...timeData };
    
    // 确保daily属性是数组
    if (!newTimeData.daily || !Array.isArray(newTimeData.daily)) {
      newTimeData.daily = getDefaultTimeData().daily;
    }
    
    // 查找并更新指定日期的数据
    const index = newTimeData.daily.findIndex((item) => item.day === day);
    if (index !== -1) {
      if (field === 'isOpen') {
        newTimeData.daily[index].isOpen = value;
      } else if (field === 'openTime') {
        newTimeData.daily[index].openTime = value.format('HH:mm');
      } else if (field === 'closeTime') {
        newTimeData.daily[index].closeTime = value.format('HH:mm');
      }
      
      // 更新工作日和周末的汇总数据
      updateSummaryFromDaily(newTimeData);
      
      setTimeData(newTimeData);
    }
  };

  // 处理工作日时间变更 - 简单模式
  const handleWorkdayChange = (field, value) => {
    const newTimeData = [...timeData];

    // 更新所有工作日
    for (let i = 0; i < 5; i++) {
      const index = newTimeData.findIndex((item) => item.day === i + 1);
      if (index !== -1) {
        if (field === 'isOpen') {
          newTimeData[index].daily.isOpen = value;
        } else if (field === 'openTime') {
          newTimeData[index].daily.openTime = value.format('HH:mm');
        } else if (field === 'closeTime') {
          newTimeData[index].daily.closeTime = value.format('HH:mm');
        }
      }
    }

    setTimeData(newTimeData);
  };

  // 处理周末时间变更 - 简单模式
  const handleWeekendChange = (field, value) => {
    const newTimeData = [...timeData];

    // 更新所有周末
    for (let i = 5; i < 7; i++) {
      const index = newTimeData.findIndex((item) => item.day === i + 1);
      if (index !== -1) {
        if (field === 'isOpen') {
          newTimeData[index].daily.isOpen = value;
        } else if (field === 'openTime') {
          newTimeData[index].daily.openTime = value.format('HH:mm');
        } else if (field === 'closeTime') {
          newTimeData[index].daily.closeTime = value.format('HH:mm');
        }
      }
    }

    setTimeData(newTimeData);
  };

  // 保存营业时间
  const handleSave = async () => {
    if (!currentStore) {
      message.warning('请先选择门店');
      return;
    }

    try {
      setLoading(true);
      
      // 确保提交的数据格式正确
      let formattedTimeData = timeData;
      
      // 如果timeData是数组，转换为BusinessHoursData格式
      if (Array.isArray(timeData)) {
        formattedTimeData = convertToBusinessHoursFormat();
      } else if (!timeData.daily || !Array.isArray(timeData.daily)) {
        // 如果timeData不是数组但缺少daily属性或daily不是数组，使用默认数据
        formattedTimeData = getDefaultTimeData();
      }
      
      const data = {
        store_id: currentStore.id,
        timeData: formattedTimeData,
      };

      const res = await saveStoreTime(data);
      if (res.success) {
        message.success('保存门店营业时间成功');
      } else {
        message.error(res.message || '保存门店营业时间失败');
      }
    } catch (error) {
      console.error('保存门店营业时间出错:', error);
      message.error('保存门店营业时间失败');
    } finally {
      setLoading(false);
    }
  };

  // 复制到全周
  const copyToAll = (sourceDay) => {
    // 创建timeData的深拷贝
    const newTimeData = { ...timeData };
    
    // 确保daily属性是数组
    if (!newTimeData.daily || !Array.isArray(newTimeData.daily)) {
      message.error('数据格式错误，无法复制');
      return;
    }

    const source = newTimeData.daily.find((item) => item.day === sourceDay);
    if (source) {
      newTimeData.daily = newTimeData.daily.map((item) => {
        if (item.day !== sourceDay) {
          return {
            ...item,
            isOpen: source.isOpen,
            openTime: source.openTime,
            closeTime: source.closeTime,
          };
        }
        return item;
      });
      
      // 更新工作日和周末的汇总数据
      updateSummaryFromDaily(newTimeData);
      
      setTimeData(newTimeData);
    }
  };

  // 获取简单模式的工作日和周末数据
  const getSimpleModeData = () => {
    const businessHoursFormat = convertToBusinessHoursFormat();
    return {
      workday: businessHoursFormat.workday,
      weekend: businessHoursFormat.weekend
    };
  };

  // 简单模式下的工作日设置
  const renderSimpleMode = () => {
    const { workday, weekend } = getSimpleModeData();

    return (
      <div>
        <Card title="工作日营业时间" size="small" extra={(
          <Button
            type="link"
            icon={<CopyOutlined />}
            onClick={() => {
              // 复制工作日设置到所有工作日
              handleWorkdayChange('isOpen', workday.isOpen);
              handleWorkdayChange('openTime', moment(workday.openTime, 'HH:mm'));
              handleWorkdayChange('closeTime', moment(workday.closeTime, 'HH:mm'));
              message.success('已应用到所有工作日');
            }}
          >
            应用到所有工作日
          </Button>
        )}>
          <Row gutter={16} align="middle">
            <Col span={6}>
              <Checkbox
                checked={workday.isOpen}
                onChange={(e) => handleWorkdayChange('isOpen', e.target.checked)}
              >
                营业
              </Checkbox>
            </Col>
            <Col span={8}>
              <TimePicker
                format="HH:mm"
                value={moment(workday.openTime, 'HH:mm')}
                onChange={(time) => handleWorkdayChange('openTime', time)}
                disabled={!workday.isOpen}
              />
            </Col>
            <Col span={2} style={{ textAlign: 'center' }}>至</Col>
            <Col span={8}>
              <TimePicker
                format="HH:mm"
                value={moment(workday.closeTime, 'HH:mm')}
                onChange={(time) => handleWorkdayChange('closeTime', time)}
                disabled={!workday.isOpen}
              />
            </Col>
          </Row>
        </Card>

        <Card title="周末营业时间" size="small" style={{ marginTop: 16 }} extra={(
          <Button
            type="link"
            icon={<CopyOutlined />}
            onClick={() => {
              // 复制周末设置到所有周末
              handleWeekendChange('isOpen', weekend.isOpen);
              handleWeekendChange('openTime', moment(weekend.openTime, 'HH:mm'));
              handleWeekendChange('closeTime', moment(weekend.closeTime, 'HH:mm'));
              message.success('已应用到所有周末');
            }}
          >
            应用到所有周末
          </Button>
        )}>
          <Row gutter={16} align="middle">
            <Col span={6}>
              <Checkbox
                checked={weekend.isOpen}
                onChange={(e) => handleWeekendChange('isOpen', e.target.checked)}
              >
                营业
              </Checkbox>
            </Col>
            <Col span={8}>
              <TimePicker
                format="HH:mm"
                value={moment(weekend.openTime, 'HH:mm')}
                onChange={(time) => handleWeekendChange('openTime', time)}
                disabled={!weekend.isOpen}
              />
            </Col>
            <Col span={2} style={{ textAlign: 'center' }}>至</Col>
            <Col span={8}>
              <TimePicker
                format="HH:mm"
                value={moment(weekend.closeTime, 'HH:mm')}
                onChange={(time) => handleWeekendChange('closeTime', time)}
                disabled={!weekend.isOpen}
              />
            </Col>
          </Row>
        </Card>
      </div>
    );
  };

  // 高级模式下的每日设置
  const renderAdvancedMode = () => {
    return (
      <Table
        dataSource={timeData?.daily || []}
        rowKey="day"
        pagination={false}
        loading={loading}
        columns={[
          {
            title: '星期',
            dataIndex: 'dayName',
            key: 'dayName',
            width: 100,
          },
          {
            title: '是否营业',
            dataIndex: 'isOpen',
            key: 'isOpen',
            width: 120,
            render: (isOpen, record) => (
              <Checkbox
                checked={isOpen}
                onChange={(e) => handleTimeChange(record.day, 'isOpen', e.target.checked)}
              />
            ),
          },
          {
            title: '开始时间',
            dataIndex: 'openTime',
            key: 'openTime',
            width: 200,
            render: (openTime, record) => (
              <TimePicker
                format="HH:mm"
                value={moment(openTime, 'HH:mm')}
                onChange={(time) => handleTimeChange(record.day, 'openTime', time)}
                disabled={!record.isOpen}
              />
            ),
          },
          {
            title: '结束时间',
            dataIndex: 'closeTime',
            key: 'closeTime',
            width: 200,
            render: (closeTime, record) => (
              <TimePicker
                format="HH:mm"
                value={moment(closeTime, 'HH:mm')}
                onChange={(time) => handleTimeChange(record.day, 'closeTime', time)}
                disabled={!record.isOpen}
              />
            ),
          },
          {
            title: '操作',
            key: 'action',
            render: (_, record) => (
              <Button
                type="link"
                icon={<CopyOutlined />}
                onClick={() => copyToAll(record.day)}
                disabled={!record.isOpen}
              >
                复制到全周
              </Button>
            ),
          },
        ]}
      />
    );
  };

  return (
    <PageContainer>
      <Card title="门店营业时间设置" extra={
        <Space>
          <Select
            placeholder="请选择门店"
            style={{ width: 200 }}
            value={currentStore?.id}
            onChange={handleStoreChange}
          >
            {stores.map((store) => (
              <Option key={store.id} value={store.id}>
                {store.name}
              </Option>
            ))}
          </Select>
          <Button type="primary" icon={<SaveOutlined />} onClick={handleSave} loading={loading}>
            保存
          </Button>
          <Button icon={<ReloadOutlined />} onClick={() => currentStore && fetchStoreTimeData(currentStore.id)}>
            刷新
          </Button>
        </Space>
      }>
        <Form form={form} layout="vertical">
          <Tabs activeKey={mode} onChange={setMode}>
            <TabPane tab="简单模式" key="simple">
              {renderSimpleMode()}
            </TabPane>
            <TabPane tab="高级模式" key="advanced">
              {renderAdvancedMode()}
            </TabPane>
          </Tabs>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default StoreTime;